<?php

namespace Admin\Controller;

use Think\Model;
use Org\Util\Sync;
use User\Api\UserApi;

/**
 * 优惠券控制器
 * @author zhangwei
 * 2015-06-19
 */
class CouponsController extends AdminController {

    /**
     * 首页
     * @author zhangwei
     * 2015-06-19
     */
    public function index() {
        $title = I('title');
        $map['batchNo'] = array('like', '%' . (string) $title . '%');
        $map['status'] = array('eq', 1);
        $list = $this->lists('coupons', $map, 'batchNo desc');
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }

    /**
     * 生成优惠券
     * @author zhangwei
     * 2015-06-19
     */
    public function add($couponstype = "", $par = "", $consume = "", $reduce = "", $cnt = "", $validityStartPeriod = "", $validityEndPeriod = "", $receiveStartPeriod = "", $receiveEndPeriod = "") {
        if (IS_POST) {
            //批次名称
            $batchNo = date("ymdHis");
            $receiveCondition_array = I('receiveCondition');
            $useCondition_array = I('useCondition');

            if ($couponstype == 1) {
                $consume = "";
                $reduce = "";
            } else {
                $par = "";
            }

            // 上传文件 
            $setting = array(
                'mimes' => '', //允许上传的文件MiMe类型
                'maxSize' => 2 * 1024 * 1024, //上传的文件大小限制 (0-不做限制)
                'exts' => 'jpg,gif,png,jpeg', //允许上传的文件后缀
            );

            /* 调用文件上传组件上传文件 */
            /*             * 修改开始* */
            $pic_driver = C('PICTURE_UPLOAD_DRIVER');
            $upload = new \Think\Upload($setting, C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$pic_driver}_CONFIG"));
            $info = $upload->upload();

            if (!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } else {// 上传成功
                //密钥
                //$code = substr(md5(NOW_TIME . $i), -10);
                $data = array('batchNo' => $batchNo, 'type' => $couponstype, 'par' => $par, 'consume' => $consume, 'reduce' => $reduce,
                    'cnt' => $cnt, 'validityStartPeriod' => strtotime($validityStartPeriod), 'validityEndPeriod' => strtotime($validityEndPeriod),
                    'receiveStartPeriod' => strtotime($receiveStartPeriod), 'receiveEndPeriod' => strtotime($receiveEndPeriod),
                    'receiveCondition' => $receiveCondition_array[0], 'useCondition' => $useCondition_array[0], 'createdate' => NOW_TIME,
                    'lastupdate' => NOW_TIME, 'fileurl' => $info["couponsphoto"]["url"]);
                $id = M('coupons')->add($data);
                if (!$id) {
                    $this->error("发布失败！");
                }
            }
            $this->success('发布成功！', U('index'));
        } else {
            $couponstype = C("COUPONS_TYPE");
            $this->assign("couponstype", $couponstype);
            $this->display();
        }
    }

    public function del() {
        $id = I('id');
        if ($id) {
            $coupons = M("coupons");

            $syncStatus = $coupons->where(array('id' => $id))->getField('syncStatus');
            if ($syncStatus != 1) {
                $syncStatus = 3;
            } else {
                $syncStatus = 0;
            }

            $data = array('status' => -1, 'syncStatus' => $syncStatus);
            $result = $coupons->where(array('id' => $id))->save($data);
            if ($result) {
                $this->success('删除成功！', U('index'));
            } else {
                $this->error("删除失败！");
            }
        }
    }

    /**
     * 导出
     * @author zhangwei
     * 2015-06-19
     */
    public function export() {

        $batchNo = I('batchNo');

        $sqltype = "select a.type  from gr_coupons a 
            where a.batchNo = '" . $batchNo . "' group by batchNo";
        $sqldata = "";
        $headArr = "";

        $Model = new Model();
        $type = $Model->query($sqltype);
        if ($type[0]['type'] == "1") {
            $sqldata = "select a.batchNo, case when a.type = 1 then '现金优惠券' end types,
            a.par,a.code,a.validityPeriod
            from gr_coupons a 
            where a.batchNo = '" . $batchNo . "'
            order by createdate,id asc";

            $headArr = array("批次名称", "优惠券类型", "面值", "密钥", "有效期");
        } else {
            $sqldata = "select a.batchNo, case when a.type = 2 then '满减优惠券' end types,
            a.consume,a.reduce,a.code,a.validityPeriod
            from gr_coupons a 
            where a.batchNo = '" . $batchNo . "'
            order by createdate,id asc";

            $headArr = array("批次名称", "优惠券类型", "消费额", "减免额", "密钥", "有效期");
        }

        $data = $Model->query($sqldata);

        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        $filename = "优惠券-" . $batchNo;

        $title = "优惠券列表";
        $this->getExcel($filename, $headArr, $data, $title);
    }

    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);

        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $objActSheet->getColumnDimension()->setWidth(20);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

    /**
     * 上推
     * @author zhangwei
     * 2015-06-23
     */
//    public function push() {
//
//        $reuslt = D("CouponsLeanCloud")->push();
//
//        $this->success('优惠券数据上推成功！', U('index'), true);
//    }
    
    
    /**
     * 上推
     * @author wangyuanlin
     * 2015-06-23
     */
    public function push(){
        
        //获取要上推的数据源
        $list = M('coupons')->where(array('syncStatus'=>array('egt', 1)))->select();

        //执行上推操作
        $list = $this->pushParse('Coupons',
            array('objectId'=>'id',
                'batchNo'=>'batchNo',
                'type'=>'type',
                'par'=>'par',
                'consume'=>'consume',
                'reduce'=>'reduce',
                'cnt'=>'cnt',
                'validityStartPeriod'=>'validityStartPeriod',
                'validityEndPeriod'=>'validityEndPeriod',
                'receiveStartPeriod'=>'receiveStartPeriod',
                'receiveEndPeriod'=>'receiveEndPeriod',
                'receiveCondition'=>'receiveCondition',
                'useCondition'=>'useCondition',
                'fileurl'=>'fileurl',
                'status'=>'status',
                'syncStatus'=>'syncStatus'),
            function($src){
                //前调函数
                $micro1 = sprintf("%03d",($src['validityStartPeriod'] - floor($src['validityStartPeriod'])) * 1000);
                $src['validityStartPeriod'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['validityStartPeriod']).'T'.date('H:i:s',$src['validityStartPeriod']).'.'.$micro1.'Z');
                
                $micro2 = sprintf("%03d",($src['validityEndPeriod'] - floor($src['validityEndPeriod'])) * 1000);
                $src['validityEndPeriod'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['validityEndPeriod']).'T'.date('H:i:s',$src['validityEndPeriod']).'.'.$micro2.'Z');

                $micro3 = sprintf("%03d",($src['receiveStartPeriod'] - floor($src['receiveStartPeriod'])) * 1000);
                $src['receiveStartPeriod'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['receiveStartPeriod']).'T'.date('H:i:s',$src['receiveStartPeriod']).'.'.$micro3.'Z');

                $micro4 = sprintf("%03d",($src['receiveEndPeriod'] - floor($src['receiveEndPeriod'])) * 1000);
                $src['receiveEndPeriod'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['receiveEndPeriod']).'T'.date('H:i:s',$src['receiveEndPeriod']).'.'.$micro4.'Z');
                
                return $src;
            },
            function($src){
                //后调函数
                //数据上推到云端后，更新本地数据的同步状态 （syncStatus ＝ 0）
                M('coupons')->where('id='.$src['objectId'])->data(array('syncStatus'=>0))->save();
                return $src;
            },
            $list);
            
       $this->success('商品分类数据上推成功！', U('index'),true);
    }
    
}
